import { constantRoutes } from '@/router'
import Layout from '@/layout'
import { getMenuNavList } from '@/api/author'
// import Cookies from 'js-cookie'
import router, { resetRouter } from '@/router'

const state = {
  routes: [],
  addRoutes: [],
  currentRoutes: [],
  navRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_CURRENT_ROUTES: (state, routes) => {
    state.currentRoutes = routes
  },
  SET_NAV_ROUTES: (state, routes) => {
    state.navRoutes = routes
  }
}
function generateTreeData(arr) {
  const newArr = []
  arr.forEach((el, index) => {
    if (el.parentId === 0) {
      const menu = {
        path: `/component${index}`,
        component: Layout,
        name: `Component${index}`,
        meta: {
          title: el.menuName,
          icon: el.icon
        },
        children: []
      }
      newArr.push(menu)
      pushRouter(arr, el, menu)
    }
  })
  return newArr
}
function pushRouter(arr, item, menu) {
  arr.forEach(el => {
    if (el.parentId === item.menuId) {
      let itemMenu = {}
      if (el.layout) {
        itemMenu = {
          path: el.url,
          component: Layout,
          meta: { title: el.menuName },
          children: [{
            path: 'index',
            name: el.componentName,
            component: resolve => require([`@/views${el.component}.vue`], resolve),
            meta: { title: el.menuName, icon: el.icon }
          }]
        }
      } else {
        itemMenu = {
          path: el.url,
          component: () => import('@/views' + el.component),
          name: el.componentName,
          meta: {
            title: el.menuName,
            icon: el.icon
          },
          children: []
        }
      }
      menu.children.push(itemMenu)
      pushRouter(arr, el, itemMenu)
    }
  })
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      getMenuNavList().then(res => {
        const allRouter = generateTreeData(res.data)
        let currentRouters = []
        allRouter.forEach(el => {
          currentRouters = currentRouters.concat([...el.children])
        })
        const newRouter = currentRouters.map(el => {
          el.component = Layout
          return el
        })
        const firstPath = newRouter[0].path + '/' + newRouter[0].children[0].path
        // 默认跳转当前路由的第一个页面
        newRouter.push({
          path: '/',
          redirect: firstPath,
          hidden: true
        })
        resolve(newRouter)
        commit('SET_CURRENT_ROUTES', newRouter)
      })
    })
  },
  changeRoutes({ commit }, routes) {
    return new Promise(resolve => {
      resetRouter()
      commit('SET_CURRENT_ROUTES', routes)
      routes.forEach(item => {
        router.addRoute(item)
      })
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
